"use client";
import type {
  SelectTabData,
  SelectTabEvent,
  TabValue,
} from "@fluentui/react-components";
import {
  Button,
  Field,
  FluentProvider,
  Input,
  makeStyles,
  Tab,
  TabList,
  Text,
  Title1,
  Title3,
  tokens,
  webLightTheme,
} from "@fluentui/react-components";
import { useState } from "react";

const useStyles = makeStyles({
  bar: {
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    padding: tokens.spacingVerticalM,
    color: tokens.colorNeutralForeground1,
    backgroundColor: tokens.colorNeutralBackground2Pressed,
  },
  can: {
    display: "flex",
    height: "100vh",
  },
  tablist: { backgroundColor: tokens.colorNeutralBackground2Pressed },
  panel: {
    flexGrow: 1,
    backgroundColor: tokens.colorNeutralBackground5Pressed,
  },
  tabpanel: {
    width: "100%",
    display: "flex",
    justifyContent: "space-around",
  },
  func: {
    backgroundColor: tokens.colorNeutralForegroundOnBrand,
    padding: tokens.spacingVerticalXL,
    margin: tokens.spacingVerticalM,
    borderRadius: tokens.borderRadiusMedium,
  },
});

function Tab1() {
  // 对应操作手册 2.2.1 添加文字水印接口 和 2.2.2 解码文字水印接口

  const styles = useStyles();
  const [txt, setTxt] = useState("");
  const [embed_text, setEmbed_text] = useState("");
  const [response, setResponse] = useState("");

  function hide_in_txt() {
    fetch("/hide_in_txt", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ txt, embed_text }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error(`HTTP 错误: ${response.status}`);
        }
        return response.json();
      })
      .then((data) => {
        if (data.success) {
          setResponse(data.data);
        } else {
          throw new Error(data.msg);
        }
      })
      .catch((error) => {
        console.error("Error:", error);
        alert("Error:" + error);
      });
  }

  const [txt2, setTxt2] = useState("");
  const [response2, setResponse2] = useState("");

  function decode_embeded_txt() {
    fetch("/decode_embeded_txt", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ txt: txt2 }),
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error(`HTTP 错误: ${response.status}`);
        }
        return response.json();
      })
      .then((data) => {
        if (data.success) {
          setResponse2(data.data);
        } else {
          throw new Error(data.msg);
        }
      })
      .catch((error) => {
        console.error("Error:", error);
        alert("Error:" + error);
      });
  }
  return (
    <div role="tabpanel" className={styles.tabpanel}>
      <div className={styles.func}>
        <Title3>（1）隐藏信息到文本</Title3>
        <Field label="文本：">
          <Input value={txt} onChange={(ev, data) => setTxt(data.value)} />
        </Field>
        <Field label="信息：">
          <Input
            value={embed_text}
            onChange={(ev, data) => {
              setEmbed_text(data.value);
            }}
          />
        </Field>
        <Button onClick={hide_in_txt}>提交</Button>
        <div>
          <Text>结果：</Text>
        </div>
        <Text>{response}</Text>
      </div>
      <div className={styles.func}>
        <Title3>（2）解码隐藏信息</Title3>
        <Field label="文本：">
          <Input value={txt2} onChange={(ev, data) => setTxt2(data.value)} />
        </Field>
        <Button onClick={decode_embeded_txt}>提交</Button>
        <div>
          <Text>结果：</Text>
        </div>
        <Text>{response2}</Text>
      </div>
    </div>
  );
}

function Tab2() {
  // 对应操作手册 2.2.3 添加音频隐水印接口 和 2.2.4 解码音频隐水印接口

  const styles = useStyles();
  const [file, setFile] = useState<File | null>(null);
  const [embed_text2, setEmbed_text2] = useState("");
  const [file_extension, setfile_extension] = useState(".wav");

  function hide_in_music_() {
    if (file === null) return alert("请选择文件");
    const formData = new FormData();
    formData.append("file", file);
    formData.append("embed_text", embed_text2);
    formData.append("file_extension", file_extension);

    fetch("/hide_in_music", {
      method: "POST",
      body: formData,
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error(`HTTP 错误: ${response.status}`);
        }

        return response.blob();
      })
      .then((blob) => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = "隐写音乐.wav";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      })
      .catch((error) => {
        console.error("Error:", error);
        alert("Error:" + error);
      });
  }

  const [file2, setFile2] = useState<File | null>(null);
  const [decode_embeded_music, setdecode_embeded_music] = useState("");

  function decode_embeded_music_() {
    if (file2 === null) return alert("请选择文件");
    const formData = new FormData();
    formData.append("file", file2);

    fetch("/decode_embeded_music", {
      method: "POST",
      body: formData,
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error(`HTTP 错误: ${response.status}`);
        }
        return response.json();
      })
      .then((data) => {
        if (data.success) {
          setdecode_embeded_music(data.data);
        } else {
          throw new Error(data.msg);
        }
      })
      .catch((error) => {
        console.error("Error:", error);
        alert("Error:" + error);
      });
  }
  return (
    <div role="tabpanel" className={styles.tabpanel}>
      <div className={styles.func}>
        <Title3>（1）隐写音乐</Title3>
        <Field label="文件：">
          <input
            type="file"
            id="file"
            onChange={(e) => setFile(e.target.files ? e.target.files[0] : null)}
          />
        </Field>
        <Field label="文字：">
          <Input
            value={embed_text2}
            onChange={(ev, data) => {
              setEmbed_text2(data.value);
            }}
          />
        </Field>
        <Field label="文件扩展名：">
          <Input
            value={file_extension}
            onChange={(ev, data) => {
              setfile_extension(data.value);
            }}
          />
        </Field>
        <Button onClick={hide_in_music_}>提交</Button>
      </div>
      <div className={styles.func}>
        <Title3>（2）解码隐写音乐</Title3>
        <Field label="文件：">
          <input
            type="file"
            id="file"
            onChange={(e) =>
              setFile2(e.target.files ? e.target.files[0] : null)
            }
          />
        </Field>
        <Button onClick={decode_embeded_music_}>提交</Button>
        <div>
          <Text>结果：</Text>
        </div>
        <Text>{decode_embeded_music}</Text>
      </div>
    </div>
  );
}

function Tab3() {
  // 对应操作手册 2.2.5 添加图像隐水印接口 和 2.2.6 解码图像隐水印接口

  const styles = useStyles();
  const [file, setFile] = useState<File | null>(null);
  const [watermark, setWatermark] = useState("");
  const [method, setMethod] = useState("spatial_domain");
  const [image, setImage] = useState("");

  function embed_watermark_blind_api() {
    if (file === null) return alert("请选择文件");
    const formData = new FormData();
    formData.append("watermark", watermark);
    formData.append("method", method);
    formData.append("file", file);

    fetch("/embed_in_image_blind", {
      method: "POST",
      body: formData,
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error(`HTTP 错误: ${response.status}`);
        }

        return response.blob();
      })
      .then((blob) => {
        const url = window.URL.createObjectURL(blob);
        setImage(url);
      })
      .catch((error) => {
        console.error("Error:", error);
        alert("Error:" + error);
      });
  }

  const [file2, setFile2] = useState<File | null>(null);
  const [length, setLength] = useState(1);
  const [extract_in_image_blind, setextract_in_image_blind] = useState("");

  function extract_in_image_blind_() {
    if (file2 === null) return alert("请选择文件");
    const formData = new FormData();
    formData.append("file", file2);
    // @ts-ignore
    formData.append("length", length);

    fetch("/extract_in_image_blind", {
      method: "POST",
      body: formData,
    })
      .then((response) => response.json())
      .then((data) => {
        if (data.success) {
          setextract_in_image_blind(data.data);
        } else {
          throw new Error(data.msg);
        }
      })
      .catch((error) => {
        console.error("Error:", error);
        alert("Error:" + error);
      });
  }
  return (
    <div role="tabpanel" className={styles.tabpanel}>
      <div className={styles.func}>
        <Title3>（1）图像盲水印嵌入</Title3>
        <Field label="文件：">
          <input
            type="file"
            id="file"
            onChange={(e) => setFile(e.target.files ? e.target.files[0] : null)}
          />
        </Field>
        <Field label="水印：">
          <Input
            value={watermark}
            onChange={(ev, data) => {
              setWatermark(data.value);
            }}
          />
        </Field>
        <Field label="方法(spatial_domain 或 frequency_domain)：">
          <Input
            value={method}
            onChange={(ev, data) => {
              setMethod(data.value);
            }}
          />
        </Field>
        <Button onClick={embed_watermark_blind_api}>提交</Button>
        {image && <img src={image} alt="图片" />}
      </div>
      <div className={styles.func}>
        <Title3>（2）图像盲水印提取</Title3>
        <Field label="文件：">
          <input
            type="file"
            onChange={(e) =>
              setFile2(e.target.files ? e.target.files[0] : null)
            }
          />
        </Field>
        <Field label="长度：">
          <Input
            type="number"
            // @ts-ignore
            value={length}
            onChange={(ev, data) => {
              // @ts-ignore
              setLength(data.value);
            }}
          />
        </Field>
        <Button onClick={extract_in_image_blind_}>提交</Button>
        <div>
          <Text>结果：</Text>
        </div>
        <Text>{extract_in_image_blind}</Text>
      </div>
    </div>
  );
}

function Tab4() {
  // 对应操作手册 2.2.7 添加图像显水印接口 和 2.2.9 添加PDF文件显水印接口 和 2.2.10 添加OFD文件显水印接口

  const styles = useStyles();
  const [file, setFile] = useState<File | null>(null);
  const [watermark, setWatermark] = useState("");
  const [
    embed_watermark_show_img_api_angle,
    setEmbed_watermark_show_img_api_angle,
  ] = useState(1);
  const [image, setImage] = useState("");

  function embed_watermark_show_img_api() {
    if (file === null) return alert("请选择文件");
    const formData = new FormData();
    formData.append("file", file);
    formData.append("watermark", watermark);
    // @ts-ignore
    formData.append("angle", embed_watermark_show_img_api_angle);

    fetch("/embed_show_img", {
      method: "POST",
      body: formData,
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error(`HTTP 错误: ${response.status}`);
        }

        return response.blob();
      })
      .then((blob) => {
        const url = window.URL.createObjectURL(blob);
        setImage(url);
      })
      .catch((error) => {
        console.error("Error:", error);
        alert("Error:" + error);
      });
  }

  const [file2, setFile2] = useState<File | null>(null);
  const [embed_show_pdf_watermark, setembed_show_pdf_watermark] = useState("");

  function embed_show_pdf() {
    if (file2 === null) return alert("请选择文件");
    const formData = new FormData();
    formData.append("file", file2);
    formData.append("value", embed_show_pdf_watermark);

    fetch("/api/v2/watermark/pdf/draw", {
      method: "POST",
      body: formData,
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error(`HTTP 错误: ${response.status}`);
        }

        return response.blob();
      })
      .then((blob) => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = file2.name;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      })
      .catch((error) => {
        console.error("Error:", error);
        alert("Error:" + error);
      });
  }

  const [file3, setFile3] = useState<File | null>(null);
  const [embed_show_ofd_watermark, setembed_show_ofd_watermark] = useState("");

  function embed_show_ofd() {
    if (file3 === null) return alert("请选择文件");
    const formData = new FormData();
    formData.append("file", file3);
    formData.append("value", embed_show_ofd_watermark);

    fetch("/api/v2/watermark/ofd/draw", {
      method: "POST",
      body: formData,
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error(`HTTP 错误: ${response.status}`);
        }

        return response.blob();
      })
      .then((blob) => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = file3.name;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      })
      .catch((error) => {
        console.error("Error:", error);
        alert("Error:" + error);
      });
  }

  return (
    <div role="tabpanel" className={styles.tabpanel}>
      <div className={styles.func}>
        <Title3>（1）显水印嵌入图像</Title3>
        <Field label="文件：">
          <input
            type="file"
            onChange={(e) => setFile(e.target.files ? e.target.files[0] : null)}
          />
        </Field>
        <Field label="水印：">
          <Input
            value={watermark}
            onChange={(ev, data) => {
              setWatermark(data.value);
            }}
          />
        </Field>
        <Field label="角度：">
          <Input
            type="number"
            // @ts-ignore
            value={embed_watermark_show_img_api_angle}
            onChange={(ev, data) => {
              // @ts-ignore
              setEmbed_watermark_show_img_api_angle(data.value);
            }}
          />
        </Field>
        <Button onClick={embed_watermark_show_img_api}>提交</Button>
        {image && <img src={image} alt="图片" />}
      </div>
      <div className={styles.func}>
        <Title3>（2）显水印嵌入pdf</Title3>
        <Field label="文件：">
          <input
            type="file"
            onChange={(e) =>
              setFile2(e.target.files ? e.target.files[0] : null)
            }
          />
        </Field>
        <Field label="水印：">
          <Input
            value={embed_show_pdf_watermark}
            onChange={(ev, data) => {
              setembed_show_pdf_watermark(data.value);
            }}
          />
        </Field>
        <Button onClick={embed_show_pdf}>提交</Button>
      </div>
      <div className={styles.func}>
        <Title3>（3）显水印嵌入ofd</Title3>
        <Field label="文件：">
          <input
            type="file"
            onChange={(e) =>
              setFile3(e.target.files ? e.target.files[0] : null)
            }
          />
        </Field>
        <Field label="水印：">
          <Input
            value={embed_show_ofd_watermark}
            onChange={(ev, data) => {
              setembed_show_ofd_watermark(data.value);
            }}
          />
        </Field>
        <Button onClick={embed_show_ofd}>提交</Button>
      </div>
    </div>
  );
}

function Tab5() {   
  // 对应操作手册 2.2.8 添加图像logo接口

  const styles = useStyles();
  const [file, setFile] = useState<File | null>(null);
  const [file2, setFile2] = useState<File | null>(null);
  const [logo_position_x, setlogo_position_x] = useState(5);
  const [logo_position_y, setlogo_position_y] = useState(5);
  const [image, setImage] = useState("");

  function add_logo() {
    if (file === null) return alert("请选择文件");
    if (file2 === null) return alert("请选择logo");
    const formData = new FormData();
    formData.append("file", file);
    formData.append("logo", file2);
    // @ts-ignore
    formData.append("logo_position_x", logo_position_x);
    // @ts-ignore
    formData.append("logo_position_y", logo_position_y);

    fetch("/add_logo", {
      method: "POST",
      body: formData,
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error(`HTTP 错误: ${response.status}`);
        }

        return response.blob();
      })
      .then((blob) => {
        const url = window.URL.createObjectURL(blob);
        setImage(url);
      })
      .catch((error) => {
        console.error("Error:", error);
        alert("Error:" + error);
      });
  }
  return (
    <div role="tabpanel" className={styles.tabpanel}>
      <div className={styles.func}>
        <Title3>给图片添加logo</Title3>
        <Field label="图像文件：">
          <input
            type="file"
            id="file"
            onChange={(e) => setFile(e.target.files ? e.target.files[0] : null)}
          />
        </Field>
        <Field label="logo文件：">
          <input
            type="file"
            id="file"
            onChange={(e) =>
              setFile2(e.target.files ? e.target.files[0] : null)
            }
          />
        </Field>
        <Field label="logo坐标x：">
          <Input
            type="number"
            // @ts-ignore
            value={logo_position_x}
            onChange={(ev, data) => {
              // @ts-ignore
              setlogo_position_x(data.value);
            }}
          />
        </Field>
        <Field label="logo坐标y：">
          <Input
            type="number"
            // @ts-ignore
            value={logo_position_y}
            onChange={(ev, data) => {
              // @ts-ignore
              setlogo_position_y(data.value);
            }}
          />
        </Field>
        <Button onClick={add_logo}>提交</Button>
        {image && <img src={image} alt="图片" />}
      </div>
    </div>
  );
}

export default function Home() {
  const styles = useStyles();
  const [selectedValue, setSelectedValue] = useState<TabValue>("tab1");

  const onTabSelect = (event: SelectTabEvent, data: SelectTabData) => {
    setSelectedValue(data.value);
  };

  return (
    <>
      <div className={styles.bar}>
        <Title1>数字水印</Title1>
      </div>
      <div className={styles.can}>
        <TabList
          selectedValue={selectedValue}
          onTabSelect={onTabSelect}
          vertical
          className={styles.tablist}
        >
          <Tab value="tab1">一、文本水印</Tab>
          <Tab value="tab2">二、音乐水印</Tab>
          <Tab value="tab3">三、图像隐水印</Tab>
          <Tab value="tab4">四、图像显水印</Tab>
          <Tab value="tab5">五、图像logo</Tab>
        </TabList>
        <FluentProvider className={styles.panel} theme={webLightTheme}>
          {selectedValue === "tab1" && <Tab1 />}
          {selectedValue === "tab2" && <Tab2 />}
          {selectedValue === "tab3" && <Tab3 />}
          {selectedValue === "tab4" && <Tab4 />}
          {selectedValue === "tab5" && <Tab5 />}
        </FluentProvider>
      </div>
    </>
  );
}
